package com.andy.app_core.net.rx;


import com.andy.app_core.net.HttpMethod;
import com.andy.app_core.net.RestCreator;

import java.io.File;
import java.util.HashMap;

import io.reactivex.Observable;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * @version V1.0
 * @描述:
 * @Company:
 * @auth: Created by AN .
 * @time: 2020/3/26 16:08
 * @des
 */
public class RxRestClient {
    private final HashMap<String,Object> PARAMS;
    private final String URL;
    private final RequestBody BODY;
    //上传下载
    private final File FILE;

    public RxRestClient(HashMap<String, Object> PARAMS,
                        String URL,
                        RequestBody BODY,
                        File FILE) {
        this.PARAMS = PARAMS;
        this.URL = URL;
        this.BODY = BODY;
        this.FILE = FILE;
    }
    public static RxRestClientBuilder create(){
        return new RxRestClientBuilder();
    }
    /**
     * 执行网络请求操作
     * @return
     */
    private Observable<String> request(HttpMethod method){
        Observable<String> observable = null;
        RxRestService service = RestCreator.getRxRestService();
        switch (method) {
            case GET:
                observable = service.get(URL, PARAMS);
                break;
            case POST:
                observable = service.post(URL, PARAMS);
                break;
            case POST_RAW:
                observable = service.postRaw(URL,BODY);
                break;
            case PUT:
                observable = service.put(URL, PARAMS);
                break;
            case PUT_RAW:
                observable = service.putRaw(URL, BODY);
                break;
            case DELETE:
                observable = service.delete(URL, PARAMS);
                break;
            case UPLOAD:
                final RequestBody requestBody = RequestBody.create(MultipartBody.FORM,FILE);
                final MultipartBody.Part body=MultipartBody.Part
                        .createFormData("file",FILE.getName(),requestBody);
                observable=service.upload(URL,body);
                break;
        }
        return observable;
    }
    //外部請求調用
    public final Observable<String> get(){
        return request(HttpMethod.GET);
    }
    public final Observable<String> post(){
        return request(HttpMethod.POST);
    }
    public final Observable<String> put(){
        return request(HttpMethod.PUT);
    }
    public final Observable<String> delete(){
        return request(HttpMethod.DELETE);
    }
    public final Observable<String> upload(){
        return request(HttpMethod.UPLOAD);
    }
    public  final Observable<ResponseBody> download(){
        return RestCreator.getRxRestService().download(URL,PARAMS);
    }

}
